package com.example.taigame;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.example.custom.image.FeedImageView;
import com.example.model.GameModel;
import com.example.utils.ResultListenner;
import com.example.utils.Utils;
import com.loopj.android.http.RequestParams;

public class SplashScreen extends BaseActivity {

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		MyApp.showProgressDialog(" ", true);
		MyApp.initListGameType();
		initData(0);
	}

	private void initData(final int position) {
		if (position < MyApp.listGameType.size() && position < Utils.gameType.length) {
			RequestParams params = new RequestParams();
			params.put("action", "getlistgame");
			params.put("type", Utils.gameType[position]);
			params.put("page", "0");
			params.put("perpage", "30");
			try {
				Utils.sendRequestAsync(Utils.SERVER, params, new ResultListenner<String>() {

					@Override
					public void onSuccess(String result) {
//						{"status":"success","servercode":"1","errormessage":null,"result":[{"0":"","id":"","1":"avartar","name":"avartar","2":"test","linkavartar":"test","3":"test","linkapk":"test","4":"10","rating":"10","5":"des","description":"des","6":"100","downnload":"100","7":"false","isonstore":"false","8":"1","type":"1","9":"test","author":"test","10":"slo","slogan":"slo"}]}
						try {
							JSONObject serverObject = new JSONObject(result);
							JSONArray serverResultArray = serverObject.getJSONArray("result");
							ArrayList<GameModel> listGameModel = new ArrayList<GameModel>();
							for(int i=0;i< serverResultArray.length();i++){
								GameModel gameModel = Utils.getGameModelFromString(serverResultArray.getString(i));
								listGameModel.add(gameModel);
							}
							MyApp.listGameType.get(position).setListGame(listGameModel);
						} catch (JSONException e) {
							e.printStackTrace();
						}
						Log.d(Utils.TAG, result);
						initData(position+1);
					}

					@Override
					public void onFail(String reasion) {
						initData(position+1);
					}
				});
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			MyApp.hideProgressDialog();
			Intent intent = new Intent(SplashScreen.this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		}
	}

}
